<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<% String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>jQuery</title>
    <link rel="icon" href="<%=basePath%>/icon/favicon-32x32.png">
    <script src="<%=basePath%>/js/jquery/jquery.min.js"></script>
    <script src="<%=basePath%>/js/main.js"></script>
</head>
<body>
<h2>文件上传</h2>

<form id="uploadForm" enctype="multipart/form-data">
    <label for="file">选择文件:</label>
    <input type="file" name="data" id="file">
    <br><br>
    <input type="submit" value="上传" id="uploadButton">
</form>

<div id="response"></div>

<script>
    // 访问路径：
    // http:\\127.0.0.1:8080/restful/jsp/uploadFile.jsp
    $(document).ready(function() {
        $('#uploadForm').on('submit', function(e) {
            e.preventDefault(); // 阻止表单的默认提交行为
            let url = '<%=basePath%>/api/upload/file';
            var formData = new FormData(this); // 获取表单数据，包括文件

            $.ajax({
                url: url,  // 服务器接收文件的路径
                type: 'POST',
                data: formData,
                contentType: false, // 必须设置为false，使用 FormData 对象传递数据
                processData: false, // 防止 jQuery 处理 data，必须设置为 false
                success: function(response) {
                    // 上传成功的回调
                    $('#response').html('<p>文件上传成功!</p>');
                },
                error: function(xhr, status, error) {
                    // 上传失败的回调
                    $('#response').html('<p>文件上传失败!</p>');
                }
            });
        });
    });
</script>
</body>
</html>
